<?php
namespace app\common\exception;
use think\facade\Env;
use Exception;
use think\exception\Handle;
use think\exception\HttpException;
class ExceptionHandle extends Handle
{

    /**
     * 全局异常处理
     * @param Exception $e
     * @return \think\Response|\think\response\Json
     * Author: LCY<409028735@qq.com>
     * Time: 2020/11/25 17:20
     * Note:
     */
    public function render(Exception $e)
    {
        if ($e instanceof HttpException) {
            //HTTP相关错误
            $code = $e->getStatusCode();
            switch ($code) {
                case 403:
                    return view(Env::get('app_path') .'common/view/public/403.html');
                case 404:
                    return view(Env::get('app_path') .'common/view/public/404.html');
                case 500:
                    return view(Env::get('app_path') .'common/view/public/500.html')->filter(function($content){
                        $replaces = config('template.tpl_replace_string');
                        if(!$replaces){
                            foreach ($replaces as $k=>$v){
                                $content = str_replace($k,$v,$content);
                            }
                        }
                        return $content;
                    });
                default:
                    return view(Env::get('app_path') .'common/view/public/dispatch.html',['code' => 0,'msg' => $e->getMessage(), 'wait' => 3]);
            }

        }

        if (config('app_debug')) {
            return parent::render($e);
        } else {
            //记录日志

            return view(Env::get('app_path') .'common/view/public/500.html')->filter(function($content){
                $replaces = config('template.tpl_replace_string');
                if(!$replaces){
                    foreach ($replaces as $k=>$v){
                        $content = str_replace($k,$v,$content);
                    }
                }
                return $content;
            });
        }


    }
}